<template>
  <div class="params">
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>
    <div class="container">
      <div class="titlebox">
        <el-alert
          title="注意: 只允许为第三级分类设置相关参数!"
          type="warning"
          effect="dark"
          show-icon
          :closable="false"
        />
      </div>

      <div class="selectbox">
        <span>选择商品分类: &nbsp;</span>
        <el-cascader
          placeholder="请选择分类"
          v-model="selectKey"
          :options="cateList"
          :props="cateProps"
          @change="handleChange"
        ></el-cascader>
      </div>
      <!-- tab切换 -->
      <el-tabs v-model="activeName" type="border-card">
        <el-tab-pane label="动态参数" name="many">
          <div class="btnbox">
            <el-button type="primary" @click="showAddDialog" size="default" class="addBtn">添加参数</el-button>
          </div>
          <el-table
            :data="manyTableData"
            border
            stripe
            row-key="attr_id"
            :expand-row-keys="expands"
          >
            <el-table-column type="expand">
              <template v-slot="scope">
                <div class="tagbox">
                  <el-tag
                    closable
                    v-for="(item, index) in scope.row.attr_vals"
                    :key="index"
                    size="small"
                    :disable-transitions="false"
                    @close="handleClosed(index, scope.row)"
                  >{{ item }}</el-tag>
                  <el-input
                    class="input-new-tag"
                    v-if="scope.row.inputVisible"
                    v-model="scope.row.inputValue"
                    ref="saveTagInput"
                    size="small"
                    @keyup.enter.native="handleInputConfirm(scope.row)"
                    @blur="handleInputConfirm(scope.row)"
                  ></el-input>
                  <el-button
                    v-else
                    class="button-new-tag"
                    size="small"
                    @click="showInput(scope.row)"
                  >新增标签</el-button>
                </div>
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index" label="#" align="center" />
            <el-table-column label="参数名称" prop="attr_name" align="center" />
            <el-table-column label="操作" align="center">
              <template v-slot="scope">
                <el-button
                  type="primary"
                  @click="showEditDialog(scope.row)"
                  :icon="EditPen"
                  size="small"
                >编辑</el-button>
                <el-button
                  type="danger"
                  @click="removeParams(scope.row.attr_id)"
                  :icon="Delete"
                  size="small"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 静态属性 -->
        <el-tab-pane label="静态属性" name="only">
          <div class="btnbox">
            <el-button type="primary" @click="showAddDialog" size="default" class="addBtn">添加属性</el-button>
          </div>
          <el-table
            :data="onlyTableData"
            border
            stripe
            row-key="attr_id"
            :expand-row-keys="expands"
          >
            <el-table-column type="expand">
              <template v-slot="scope">
                <div class="tagbox">
                  <el-tag
                    closable
                    size="samll"
                    v-for="(item, index) in scope.row.attr_vals"
                    :key="index"
                    :disable-transitions="false"
                    @close="handleClosed(index, scope.row)"
                  >{{ item }}</el-tag>
                  <el-input
                    class="input-new-tag"
                    v-if="scope.row.inputVisible"
                    v-model="scope.row.inputValue"
                    ref="saveTagInput"
                    size="small"
                    @keyup.enter.native="handleInputConfirm(scope.row)"
                    @blur="handleInputConfirm(scope.row)"
                  ></el-input>
                  <el-button
                    v-else
                    class="button-new-tag"
                    size="small"
                    @click="showInput(scope.row)"
                  >新增标签</el-button>
                </div>
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index" label="#" align="center" />
            <el-table-column label="属性名称" prop="attr_name" align="center" />
            <el-table-column label="操作" align="center">
              <template v-slot="scope">
                <el-button
                  type="primary"
                  @click="showEditDialog(scope.row)"
                  :icon="EditPen"
                  size="small"
                >编辑</el-button>
                <el-button
                  type="danger"
                  @click="removeParams(scope.row.attr_id)"
                  :icon="Delete"
                  size="small"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
      <!-- 添加对话框 -->
      <el-dialog
        :title="'添加' + titleText"
        v-model="addDialogVisible"
        width="50%"
        @close="addFormRef.resetFields()"
      >
        <el-form :model="formData" :rules="rules" ref="addFormRef" label-width="20%">
          <el-form-item :label="titleText" prop="attr_name">
            <el-input v-model="formData.attr_name" style="width: 80%"></el-input>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="addDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="addParams(addFormRef)">确 定</el-button>
          </span>
        </template>
      </el-dialog>
      <!-- 编辑对话框 -->
      <el-dialog
        :title="'编辑' + titleText"
        v-model="editDialogVisible"
        width="50%"
        @close="formData.attr_name=''"
      >
        <el-form :model="formData" :rules="rules" ref="editFormRef" label-width="20%">
          <el-form-item :label="titleText" prop="attr_name">
            <el-input v-model="formData.attr_name" style="width: 80%"></el-input>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="editDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="editParams(editFormRef)">确 定</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
</template>
<script setup>
import { reactive, ref, computed } from "vue";
import {
  getReports,
  getCategories,
  getCateAttrs,
  postCateAttrs,
  putCateAttrs,
  deleteCateAttrs
} from "../tools/ajax.js";
import { useRoute, useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { EditPen, Delete } from "@element-plus/icons-vue";

const route = useRoute();
const router = useRouter();

const editDialogVisible = ref(false);
const editFormRef = reactive({});
const addDialogVisible = ref(false);
const activeName = ref("many");
const addFormRef = reactive({});
const formData = reactive({});
const expands = reactive([]);
const selectKey = ref("");
const manyTableData = reactive([]);
const onlyTableData = reactive([]);
const cateList = reactive([]);
const cateProps = {
  expandTrigger: "hover",
  label: "cat_name",
  value: "cat_id",
  children: "children",
  emitPath: false
};
getCategories().then(res => {
  if (res.meta.status != 200) {
    ElMessage.error(res.meta.msg);
  } else {
    ElMessage.success(res.meta.msg);
    cateList.push(...res.data);
  }
});

function handleChange() {
  getCateAttrs({
    id: selectKey.value,
    sel: "many"
  }).then(res => {
    if (res.meta.status !== 200)
      return ElMessage.error("获取此分类动态参数失败!");
    res.data.forEach(item => {
      if (item.attr_vals.length === 0) {
        item.attr_vals = [];
      } else {
        item.attr_vals = item.attr_vals.split(" ");
      }
    });
    manyTableData.splice(0);
    manyTableData.push(...res.data);
  });

  // 请求此分类的静态属性
  getCateAttrs({
    id: selectKey.value,
    sel: "only"
  }).then(res => {
    if (res.meta.status !== 200) {
      return ElMessage.error("获取此分类静态属性失败!");
    } else {
      res.data.forEach(item => {
        if (item.attr_vals.length === 0) {
          item.attr_vals = [];
        } else {
          item.attr_vals = item.attr_vals.split(" ");
        }
      });
      onlyTableData.splice(0);
      onlyTableData.push(...res.data);
    }
  });
}

const rules = {
  attr_name: [
    {
      required: true,
      message: "请输入正确的名称",
      trigger: "change"
    },
    {
      min: 2,
      max: 10,
      message: "名称长度在2-10之间",
      trigger: "change"
    }
  ]
};

const titleText = computed(() => {
  if (activeName.value == "many") {
    return "动态参数";
  } else {
    return "静态属性";
  }
});
function showAddDialog() {
  if (selectKey.value) {
    addDialogVisible.value = true;
  } else {
    ElMessage.warning("请先选择分类!");
  }
}
function addParams(form) {
  form.validate(bool => {
    if (!bool) {
      ElMessage.error("请正确填写名称!");
    } else {
      postCateAttrs({
        id: selectKey.value, //分类id
        attr_name: formData.attr_name,
        attr_sel: activeName.value
      }).then(res => {
        if (res.meta.status != 201) {
          return ElMessage.error(res.meta.msg);
        } else {
          ElMessage.success(res.meta.msg);
          addDialogVisible.value = false;
          handleChange();
        }
      });
    }
  });
}

function showEditDialog(data) {
  formData.attr_name = data.attr_name;
  formData.attr_id = data.attr_id;
  formData.attr_vals = data.attr_vals;
  editDialogVisible.value = true;
}
function editParams(form) {
  form.validate(bool => {
    if (!bool) {
      ElMessage.error("请正确填写名称!");
    } else {
      putCateAttrs({
        id: selectKey.value,
        attr_id: formData.attr_id,
        attr_name: formData.attr_name,
        attr_sel: activeName.value,
        attr_vals: formData.attr_vals.join(" ")
      }).then(res => {
        if (res.meta.status != 200) {
          return ElMessage.error(res.meta.msg);
        } else {
          ElMessage.success(res.meta.msg);
          editDialogVisible.value = false;
          handleChange();
        }
      });
    }
  });
}
function removeParams(attr_id) {
  ElMessageBox.confirm("此操作将永久删除此属性或参数, 是否继续?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(() => {
      deleteCateAttrs({
        id: selectKey.value,
        attr_id
      }).then(res => {
        if (res.meta.status !== 200) {
          ElMessage.error(res.meta.msg);
        } else {
          ElMessage.success(res.meta.msg);
          handleChange();
        }
      });
    })
    .catch(() => {
      ElMessage.warning("取消删除");
    });
}
function showInput(row) {
  row.inputVisible = true;
  expands[0] = row.attr_id;
}
function handleInputConfirm(row) {
  if (row.inputValue.trim().length == 0) {
    row.inputValue = "";
    row.inputVisible = false;
  } else {
    row.attr_vals.push(row.inputValue.trim());
    row.inputValue = "";
    row.inputVisible = false;
    uploadData(row);
  }
}
function uploadData(row) {
  putCateAttrs({
    id: row.cat_id,
    attr_id: row.attr_id,
    attr_name: row.attr_name,
    attr_sel: row.attr_sel,
    attr_vals: row.attr_vals.join(" ")
  }).then(res => {
    if (res.meta.status != 200) {
      ElMessage.error(res.meta.msg);
    } else {
      ElMessage.success(res.meta.msg);
      editDialogVisible.value = false;
      row = res.data;
    }
  });
}
function handleClosed(index, row) {
  row.attr_vals.splice(index, 1);
  uploadData(row);
}
</script>

<style scoped>
.titlebox {
  margin-bottom: 20px;
}
.btnbox {
  margin-bottom: 10px;
  display: flex;
}
.tagbox {
  padding: 5px 20px;
}
.input-new-tag {
  width: 72px;
}
.el-tag {
  margin-right: 10px;
}
.selectbox {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  font-size: 16px;
}
.el-alert__content {
  display: flex;
  align-items: center;
}
.el-alert {
  margin: 20px 0 0;
}
.el-alert:first-child {
  margin: 0;
}
</style>